var salt = sessionStorage.getItem('usersalt');
layui.config({
	base: '../../../js/',
})
layui.use(['form', 'layer', 'laydate', 'table', 'multiSelect'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery,
		laydate = layui.laydate,
		formSelects = layui.formSelects,
		table = layui.table;

	/*验证登录*/
	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);
	}

	/*时间选择器*/
	laydate.render({
		elem: '#statdate',
		trigger: 'click'
	});

	laydate.render({
		elem: '#enddate',
		trigger: 'click'
	});

	/*筛选*/
	$('body').on('click',"#seleCheck,#findscri", function() {
    getDangerList()
	});

	/*搜索*/
	$('#findscri').on('click', function() {
		var inptext = $('#inptext').val();
		var box = /\s/g;
		var param = inptext.replace(box, '');
	});
	var company;
	/*取出所有的单位*/
	function getAllDanwei() {
		$.ajax({
			url: url + 'baseEnt/getAllEnt',
			dataType: 'json',
			async: false,
			type: "POST",
			data: {},
			success: function(data) {
				$('#danwei').empty();
				if(data.code == 0) {
					var list = data.data;
					company = list;
				}

			},
			error: function(error) {
				console.log("获取失败");
			}
		});
	}

	getAllDanwei();

    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: zTreeOnCheck
        }
    };
	var zNodes = company;
	$.fn.zTree.init($("#danwei"), setting, zNodes);

	function getSydwVal() {
		var treeArr = [];
		var treeObj = $.fn.zTree.getZTreeObj("danwei");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			treeArr.push(nodes[i].id); //获取选中节点的值
		}
		return treeArr;
	}
	$('#resclas').click(function() {
		$('#danwei').show();
	});

	function zTreeOnCheck(event, treeId, treeNode) {
		var nval = "";
		var treeObj = $.fn.zTree.getZTreeObj("danwei");
		var nodes = treeObj.getCheckedNodes(true);
		for(var i = 0; i < nodes.length; i++) {
			nval += nodes[i].name + ",";
		}
		$('#resclas').val(nval.substr(0, nval.length - 1));
	};
	/*------------tree.end------------*/

	var tableIns;
  function getDangerList(searchText) {
    var sydwArr = getSydwVal();
    if(!searchText) {
      searchText = null;
    }

    var types = [];
    var obj_type = document.getElementById("type");
    for(var i = 0; i < obj_type.options.length; i++) {
      if(obj_type.options[i].selected) {
        types.push(obj_type.options[i].value); // 收集选中项
      }
    }

    tableIns = table.render({
      elem: '#dangerList',
      method: 'post',
      url: url + 'questionPaper/getQuestionPaperPage',
      where: {
        Token: salt, //用户码
        examType:$("#type").val(),
        title:$("#inptext").val(),
        entId:sydwArr.toString(),
        startTime:$("#statdate").val(),
        endTime:$("#enddate").val()
      },
      cellMinWidth: 95,
      page: true,
      height: "full-125",
      id: "dangerListTable",
      cols: [
        [{
          type: "numbers",
          width: 50,
          title: "序号",
        },
          {
            type: "checkbox",
            width: 50
          },
          {
            field: 'title',
            title: '试卷名称',
            align: 'center',
            templet: function(p) {
              if(p.title){
                return "<div class='title' id='"+p.id +"' onclick=showDetail('" + p.id + "')>"+p.title+"</div>";
              }
            }
          },
          {
            field: 'name',
            title: '总题数',
            align: 'center',
            templet: function(p) {
              var arr = p.qusetionId.split(",");
              return "<div onclick=showDetail('" + p.id + "')>" + arr.length + "</div>"
            }
          },
          {
            field: 'total',
            title: '总分值',
            align: 'center',
            templet: function(p) {
              if(p.total) {
                return "<div onclick=showDetail('" + p.id + "')>" + p.total + "</div>";
              } else {
                return "<div></div>"
              }
            }
          },
          {
            field: 'examType',
            title: '考试类型',
            align: 'center',
            templet: function(p) {
              if(p.examType == 0){
                return "<div onclick=showDetail('" + p.id + "')>" + "模拟练习</div>";
              }else if (p.examType == 1){
                return "<div onclick=showDetail('" + p.id + "')>" + "班组测试</div>";
              }else if (p.examType == 2){
                return "<div onclick=showDetail('" + p.id + "')>" + "专项测试</div>";
              }
            }

          },
          {
            field: 'numberNo',
            title: '答题期限',
            align: 'center',
            width:300,
            templet: function(p) {
              if(p.startTime) {
                return "<div onclick=showDetail('" + p.id + "')>" + initDate(p.startTime) + "至" + initDate(p.endTime) + "</div>";
              } else {
                return "<div>不限期</div>"
              }
            }
          },
        ]
      ],
      done: function(res, curr, count) {

      }
    });

  }
  getDangerList();

	//新增
	$(".addNews_btn").click(function() {
		$(".model").show();
	});


	//题库
	$(".subject_btn").click(function() {
		location.href = "../subject/subject.html"

	});

	//导出
	$(".export_btn").click(function() {

	});
	//导入
	$(".import_btn").click(function() {
		layer.open({
			type: 2,
			title: false,
			content: "page/404.html",
			area: ['700px', '300px']
		});
	});

  $(".import_btn").click(function() {
    layer.open({
      type: 2,
      title: false,
      content: "page/404.html",
      area: ['700px', '300px']
    });
  });

  $(".del_btn").click(function() {
    var checked = $("td input[type=checkbox]:checked");
    var idArr = [];
    if(checked.length == 0){
      alert("请选择试卷！")
      return
    }
    checked.each(function () {
      idArr.push($(this).parents("tr").find(".title").attr("id"));
    })
    $.post(url+"questionPaper/delQuestionPaper",{id:idArr.toString(),Token:salt},function (data) {
      if(data.code == 0){
        layer.msg('删除成功');
        tableIns.reload()
      }else{
        alert(data.msg)
      }
    })
  });
})


function showDetail(checkId) {
	// location.href = '../addtest/add.html?id=' + checkId + "&detail=true";
    location.href = 'detail.html?id='+checkId
}

function initDate(data) {
  var time = new Date(data);
  var str = time.getFullYear()+"年"+(time.getMonth()+1)+"月"+time.getDate()+"日";
  return str
}

$(".edit_btn").click(function () {
  var checked = $("td input[type=checkbox]:checked");
  var id;
  if(checked.length == 0){
    alert("请选择试卷！")
    return
  }
  if(checked.length > 1){
    alert("只能编辑一张试卷！")
  }
  id = checked.parents("tr").find(".title").attr("id");
  location.href = "../addtest/add.html?id="+id+"&edit=true";
})
